package reg.data;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import reg.domain.Noticia;


public class JDBCNoticiaDAO implements INoticiaDAO {

	
	@Override
	public List<Noticia> seleccionaTodasNoticias() {
		Connection conn = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
		List<Noticia> searchResults = new LinkedList<Noticia>();
		ResultSet result = null;

		try {
			String sql = "SELECT * FROM Noticias";
			stmt = conn.prepareStatement(sql); 
			stmt.executeQuery();
			result = stmt.executeQuery();

			while (result.next()) {
				Noticia n = new Noticia();
				n.setTitulo(result.getString("titulo"));
				n.setContenido(result.getString("contenido"));
				n.setFecha(result.getDate("fecha"));
				// TODO SetUsuarioCreador
				n.setUsuarioCreador(null);
				searchResults.add(n);
			}
			
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			ConnectionManager.getInstance().checkIn(conn);
			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		return searchResults;
	}
	

	@Override
	public List<Noticia> seleccionaNoticiasAPartirDeFecha(Date fechaUltimoLogin) {
		Connection conn = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
		List<Noticia> searchResults = new LinkedList<Noticia>();
		ResultSet result = null;

		try {
			String sql = "SELECT * FROM Noticias WHERE fecha > '"+fechaUltimoLogin+"'";
			stmt = conn.prepareStatement(sql); 
			stmt.executeQuery();
			result = stmt.executeQuery();

			while (result.next()) {
				Noticia n = new Noticia();
				n.setTitulo(result.getString("titulo"));
				n.setContenido(result.getString("contenido"));
				n.setFecha(result.getDate("fecha"));
				// TODO SetUsuarioCreador
				n.setUsuarioCreador(null);
				searchResults.add(n);
			}
			
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			ConnectionManager.getInstance().checkIn(conn);
			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		return searchResults;
	}

	
}
